import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { alertDispatch } from '@/utils'
import CheckLogin from '@/components/CheckLogin'
import { homeDefApi } from '@/Api'
import { useHistory } from 'react-router-dom'
import ArrowRightIcon from '@material-ui/icons/ArrowRight';
import './home.less'
import bannerImg from '@/assets/images/home/xiaolang.png'
import ExamListItem from '@/components/ExamListItem'
function Home(props) {
    const history = useHistory()
    const [title,setTitle] = useState('')
    const [collect,setCollect] = useState(0)
    const [study,setStudy] = useState(2)
    const [wrong,setWrong] = useState(0)
    const [total,setTotal] = useState(0)
    const [exemItems,setExemItems] = useState([])

    // eslint-disable-next-line 
    useEffect(async ()=>{
        try{
            const res = await homeDefApi()
            const {exam, collect, study,wrong,exemItems} = res.data
            // console.log(exemItems);
            if(res.errCode === 0){
                setTitle(exam.title)
                setCollect(collect)
                setStudy(study)
                setWrong(wrong)
                setTotal(exam.itemCount)
                setExemItems(exemItems)
            }
        }catch(err){
            if(err){
                if(err.response.data.errCode === 1002){
                    // 提示
                    props.error(err.response.data.message)
                    // 跳转
                    history.push('/login')
                }
            }
        }
    },[history,props])
    return (
        <div className="home">
            <div className="top-header">
                <h2>{title}</h2>
                <div className="change-subject">
                    <span>切换考试科目</span>
                    <ArrowRightIcon />
                </div>
            </div>
            <div className="banner">
                <div className="banner-img">
                    <img src={bannerImg} alt="" />
                </div>
                <div className="info">
                    <p className="calc">
                        <span>已学{study}题</span> | <span>共{total}题</span>
                    </p>
                    <p className="info-bot">
                        <span>
                            <span className="num">{wrong}</span>
                            <span>错题</span>
                        </span>
                        <span>
                            <span className="num">{collect}</span>
                            <span>收藏</span>
                        </span>
                    </p>
                </div>
            </div>
            <div className="exam-list">
                {
                   exemItems.map(item=>{
                       return <ExamListItem key={item.actionCode} data={item}/>
                   })
                }
            </div>
        </div>
    )
}

export default connect(null, alertDispatch)(CheckLogin(Home))
